﻿using System;
using System.Linq;
using Loki.IoC;
using Loki.Model;
using Luna.Data.Configuration;
using Luna.Data.CRM;

namespace Luna.Model.CRM
{
    internal class CacheConfiguration : ProviderCacheConfiguration<IContactProvider>
    {
        public readonly ContainerConfiguration<Account, Guid> ACCOUNTS = new ContainerConfiguration<Account, Guid>()
        {
            FullLoader = () => Provider.AccountGetAll().Select(x => new Account(x)),
            PrimaryKey = new UniqueKeyConfiguration<Account, Guid>()
            {
                Indexer = x => x.ID,
                Loader = x => { var buffer = Provider.AccountGet(CreateReference(x)); return buffer != null ? new Account(buffer) : null; }
            }
        };

        public readonly ContainerConfiguration<Category, Guid> CATEGORIES = new ContainerConfiguration<Category, Guid>()
        {
            FullLoader = () => Provider.CategoryGetAll().Select(x => new Category(x)),
            PrimaryKey = new UniqueKeyConfiguration<Category, Guid>()
            {
                Indexer = x => x.ID,
                Loader = x => { var buffer = Provider.CategoryGet(CreateReference(x)); return buffer != null ? new Category(buffer) : null; }
            }
        };

        public readonly ContainerConfiguration<Contact, Guid> CONTACTS = new ContainerConfiguration<Contact, Guid>()
        {
            FullLoader = () => Provider.ContactGetAll().Select(x => new Contact(x)),
            PrimaryKey = new UniqueKeyConfiguration<Contact, Guid>()
            {
                Indexer = x => x.ID,
                Loader = x => { var buffer = Provider.ContactGet(CreateReference(x)); return buffer != null ? new Contact(buffer) : null; }
            },
            Indexes = new IIndexConfiguration<Contact>[]
            {
                new IndexConfiguration<Contact, Guid>()
                {
                    Indexer = x => x.Data.AccountID,
                    Loader = x => Provider.ContactGetAllByAccount(CreateReference((Guid)x)).Select(c => new Contact(c))
                }
            }
        };

        private IReferenceData CreateReference(Guid id)
        {
            var buffer = Context.Get<IReferenceData>();
            buffer.PK = id;
            return buffer;
        }
    }
}